/**
 * 添加用户弹出框 （查看，修改，添加）
 */
import React from 'react';
import { connect } from 'umi';
import { Modal, message, Button } from 'antd';
import DataPop from './Pop/DataPop';
import ApiPop from './Pop/ApiPop';
import Apply from './Pop/Apply';
import moment from 'moment';
import { Color } from '@antv/attr';

@connect(({ MyRole, user }) => ({
  MyRole,
  user,
})) 
export default class extends React.Component {
  forms = {};

  // 权限申请添加
  applyPower = async obj => {
    let rs=await this.props.dispatch({
      type: 'MyRole/applyPower',
      payload: obj,
    });
    if(rs.success){
      message.success("操作成功");
      this.onClose();
    }
    if(!rs.success){
      message.error("操作失败")
    }
  };

  // 测试链接
  getDataTest = async id => {
    let rs = await this.props.dispatch({
      type: 'MyRole/getDataTest',
      payload: id,
    });
    // console.log(rs,"测试链接")
    if (rs.success) {
      message.success("测试成功")
      // this.onClose();
    }
    if(!rs.success){
      message.error("操作失败")
    }
  };
  // 改变footer ，根据 组件状态不同，返回footer 不同
  footerCheck = () => {
    const { addVisibleModalType, testId } = this.props.MyRole;
    if (addVisibleModalType === 'apiSee') return null;
    if (addVisibleModalType === 'dataSee') {
      return (
        <div
          // style={{
          //   textAlign: 'center',
          // }}
        >
          <Button
            onClick={() => {
              if(testId!==""){
                // 数据源测试连接
                this.getDataTest(testId);
              }
            }}
            type="primary"
            style={{padding:"5px 16px"}}
          >
            测试连接
          </Button>
        </div>
      );
    }
    if (addVisibleModalType === 'apply') {
      return (
        <div
          // style={{
          //   textAlign: 'center',
          // }}
        >
          <Button onClick={this.handleOk} type="primary" style={{padding:"5px 16px"}}>
            确定
          </Button>
          <Button onClick={this.onClose} style={{border: "1px solid #D9D9D9",padding:"5px 16px",color:"rgba(0, 0, 0, 0.65)"}}>
            取消
          </Button>
        </div>
      );
    }
  };
  //根据状态不同，返回弹窗组件
  judgePop() {
    const { addVisibleModalType } = this.props.MyRole;
    if (addVisibleModalType === 'dataSee') return <DataPop />;
    if (addVisibleModalType === 'apiSee') return <ApiPop />;
    if (addVisibleModalType === 'apply') {
      return <Apply init={form => (this.forms.MyRolePopApply = form)} />;
    }
  }

  //获取弹窗type类型,判断modal标题
  getTitle = () => {
    const { addVisibleModalType } = this.props.MyRole;
    if (addVisibleModalType === 'dataSee') return '查看数据源连接';
    if (addVisibleModalType === 'apiSee') return 'API';
    if (addVisibleModalType == 'apply') return '数据源权限申请';
  };

  //关闭弹窗
  onClose = () => {
    this.props.dispatch({
      type: 'MyRole/setState',
      payload: { addVisible: false },
    });
  };
  // modal大小
  size = () => {
    const { addVisibleModalType } = this.props.MyRole;
    if (addVisibleModalType === 'dataSee') return '600px';
    if (addVisibleModalType === 'apiSee') return '900px';
    if (addVisibleModalType === 'apply') return '600px';
  };
  // 点击确定
  handleOk = async () => {
    const { addVisibleModalType } = this.props.MyRole;
    //确定申请权限
    if (addVisibleModalType === 'apply') this.add();
  };

  // 申请权限
  add = async () => {
    const { allDataTypeList, workSpaceName } = this.props.MyRole;
    const { MyRolePopApply } = this.forms;
    const { user } = this.props.user;
    var attr = [MyRolePopApply?.validateFields()];
    var [userFormData] = await Promise.all(attr);
    console.log(userFormData,"userFormData")
    // 获取选中数据源名称对象
    let businessName = allDataTypeList.filter(val => {
      return val.id === userFormData.businessId;
    });
    // 获取选中的工作空间对象
    let workspace = workSpaceName.filter(val => {
      return (val.id = userFormData.workSpaceId);
    });
    //调用申请权限接口 携带数据
    let obj = {
      businessType: 1,
      businessName:businessName[0].name,
      businessId:userFormData.businessId,
      applyUserId:user.id,
      applyUserName:user.name,
      startTime:moment(userFormData.time[0]._d).valueOf(),
      endTime:moment(userFormData.time[1]._d).valueOf(),
      reason:userFormData.reason,
      expandField:JSON.stringify({
        workspaceId: userFormData.workSpaceId,
        type: workspace[0].modelType,
        dataSourceType:businessName[0].dataSourceType
      })
    };
    // 调用接口 数据源申请
    this.applyPower(obj);
  };

  render() {
    const { addVisible } = this.props.MyRole;
    return (
      <Modal
        title={this.getTitle()}
        width={this.size()}
        onCancel={this.onClose}
        visible={addVisible}
        footer={this.footerCheck()}
        destroyOnClose={true}
        centered={true}
      >
        {this.judgePop()}
      </Modal>
    );
  }
}
